/* eslint-disable */
/**
 * Created by tangqiaojie <2482366539@qq.com> on 2020/3/30 0030
 */

import { nextTick } from '../../lib/utils.js';
import { openFakeWin } from "./tool.js";

const urls=[
  {
    url:"https://etax.chongqing.chinatax.gov.cn:8002/js3qbbcxtax/index.html",
    type:""
  }
]

let cssStyle = `
    .table-box {
        border-collapse: collapse;
        width: 100%;
        font-size: 14px;
        color: #333;
    }
    .table-box .spring_tr {
			display: none;
		}
    .table-box input {
        background: #fff;
        text-align: right;
        width: 100%;
        border: none;
    }
    .table-box td {
        border: 1px solid #ddd;
    }
    .table-box .hidden {
        display: none;
    }
    .table-box table .txt-indent-2 {
        text-indent: 2em;
    }

    .table-box table .txt-indent-4 {
        text-indent: 4em;
    }
    .table-box table .txt-indent-6 {
        text-indent: 6em;
    }
    .table-box table thead td {
        border: none;
    }
    .table-box .table-title {
        text-align: center;
    }
    .table-box .mini-checkboxlist-item {
        display: inline-block;
    }
    .table-box .mini-checkboxlist-item input {
        width: auto;
    }
    .table-box .mini-checkboxlist-item label {
        display: inline-block;
    }
`;

let zzsResult = false;
let fjsResult = false;
// 处理html 片段
const dealHtmlPargram = (pargram, className = "", style = "") => {
  return `<table ${style} class="${className}">${pargram}</table>`;
};

const saveTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: 'asyncTableDetail',
      data: tableContent
    },
    '*'
  );
};

const sendTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: 'asyncTableDetailRequest'
    },
    '*'
  );
};

const asyncMainTable = () => {

};

const asyncZzs=()=>{
  nextTick(()=>{
    if($("#增值税月报（一般纳税人）").length && $("#增值税月报（一般纳税人）").contents().find('#BBPage').length){
      let win=$("#增值税月报（一般纳税人）").length && $("#增值税月报（一般纳税人）").contents().find('#BBPage')[0].contentWindow;
      if(win.document.querySelector("#print_TableOne h3")) {
        let tableContent = {
          declareType: '增值税',
          title: win.document.querySelector("#print_TableOne h3").innerText,
          html: dealHtmlPargram(win.document.querySelector('#Table_all').innerHTML),
          css: ''
        };
        console.log(tableContent);
        saveTableDetail(tableContent);
        
        setTimeout(()=>{
          window.postMessage(
            {
              event: 'baoBiaoDetailBack',
              data: 'zeroTax'
            },
            '*'
          );
          setTimeout(() => {
            window.close();
          }, 1000);
        },1000);
        return true;  
      }
    }
  })
};

const startAsyncTableDetail=()=>{
  if(window.location.href.includes('https://etax.chongqing.chinatax.gov.cn:8002/js3qbbcxtax/index.html')){
    window.postMessage({
      event: 'getAsyncTableDetailStartStatus'
    }, '*')
    window.addEventListener(
      'message',
      async function({ data }) {
        if (data.sender !== 'content-script') {
          return false;
        }
        if (data.event === 'getAsyncTableDetailStartStatusBack') {
          if(data.data.isStart) {
            asyncZzs();
          }
        }
      }
    )
  }
};

const startAsyncTable = async (data) => {
  // console.log(data);
  zzsResult = !!data.tableDetailList.find(item => item.declareType === '增值税');
  fjsResult = !!data.tableDetailList.find(item => item.declareType === '附加税（费）申报');
  nextTick(() => {
    let indexContent = $('#indexContent');
    if(indexContent.length && indexContent.contents().find('#bizContent').length) { 
      let bizContent = indexContent.contents().find('#bizContent');
      let timer = setInterval(async () => {
        if(bizContent.contents().find('.datagrid-body table').length) { 
          clearInterval(timer);timer = null;
          let trs = bizContent.contents().find('.datagrid-body table tr');
          let zzsTr = Array.from(trs).find(item => {
            return $(item).find('td[field=YZPZZL_MC]').text().includes('增值税');
          });
          let fjsTr = Array.from(trs).find(item => {
            return $(item).text().includes('附加税（费）申报');
          });
          if(!zzsResult) {
            zzsResult = await xqyZZS(zzsTr);
            if(zzsResult) asyncTableDetail();
          } else if(!fjsResult) {
            fjsResult = await xqyfjs(fjsTr);
          } else {
            setTimeout(() => {
              window.postMessage(
                {
                  event: 'asyncTableDetailRequest',
                  data: 'zeroTax'
                },
                '*'
              );
              setTimeout(() => {
                window.close();
              }, 1000);
            }, 100);
          }
          
        }
      }, 200);
      return true;
    }
  })
}

const xqyfjs = async (zzsTr) => {
  return new Promise((resolve, rejcet) => {
    let zzsTd = Array.from($(zzsTr).find('td')).find(item => $(item).text().includes('查询打印'));
    let zzsTdA = Array.from($(zzsTd).find('a')).find(item => $(item).text().includes('查询打印'));
    if(zzsTdA) zzsTdA.click();
    setTimeout(() => {
      window.close();
    }, 2000);
  }) 
}

const xqyZZS = async (zzsTr) => {
  return new Promise((resolve, rejcet) => {
    let zzsTd = Array.from($(zzsTr).find('td')).find(item => $(item).text().includes('查询打印'));
    let zzsTdA = Array.from($(zzsTd).find('a')).find(item => $(item).text().includes('查询打印'));
    if(zzsTdA) zzsTdA.click();
    setTimeout(() => {
      let num = 0;
      let timer = setInterval(async () => {
        let indexContent = $('#indexContent');
        let lists = "#Layout_PZZL_center > div.panel.layout-panel.layout-panel-west > div > div > div.panel.layout-panel.layout-panel-center > div > div > div > div.datagrid-view > div.datagrid-view2 > div.datagrid-body > table > tbody tr";
        if(indexContent.length && indexContent.contents().find(lists).length) {
          clearInterval(timer);timer = null;
          // 同步申报表
          let zzsResult = await xqyzzsflzlTable();
          resolve(zzsResult);
          return true;
        }
        num ++;
        if(num > 10) {
          clearInterval(timer);timer = null;
          num = 0;
          if (Array.from($(zzsTr).find('td')).find(item => $(item).attr('title') === '10101')) {
            window.close();
          }
        }
      }, 200);   
    }, 1000);
  }) 
}
const xqyzzsflzlTable = async () => {
  return new Promise((resolve, rejcet) => {
    nextTick(() => {
      let indexContent = $('#indexContent');
      if(indexContent.length && indexContent.contents().find('#BB_0102000000').length) {
        $('#indexContent').contents().find('#BBList').val('0102000001');
        $('#indexContent').contents().find('#BBList').change();
        nextTick(() => {
          if( document.querySelector("body > div:nth-child(1) > table > tbody > tr:nth-child(2) > td.ui_c > div > table > tbody > tr:nth-child(3) > td > div > input")) {
            document.querySelector("body > div:nth-child(1) > table > tbody > tr:nth-child(2) > td.ui_c > div > table > tbody > tr:nth-child(3) > td > div > input").click();
            let DIV_0102000000 = indexContent.contents().find('#BB_0102000000');
            if(DIV_0102000000.length) {
              let table1 = DIV_0102000000.contents();
              if(table1.find('#TableOne').length){
                // 
                let tableOne = dealHtmlPargram(table1.find('#TableOne')[0].innerHTML, '', 'width="100%"');
                let tableTwo = dealHtmlPargram(table1.find('#TableTwo')[0].innerHTML, 'table-box', 'width="100%"');
                let tableContent = {
                  declareType: '增值税',
                  title: table1.find('#TableOne tbody > tr:nth-child(1) > td > h3').text().replace(/\s+/g, ''),
                  html: tableOne + tableTwo,
                  css: cssStyle
                };
                saveTableDetail(tableContent);
                setTimeout(() => {
                  indexContent.contents().find('#return_open').click();
                  setTimeout(() => {
                    resolve(true)
                  }, 1000);
                }, 500);
                return true 
              }
            }
          } else {
            let DIV_0102000000 = indexContent.contents().find('#BB_0102000000');
            let DIV_0102000001 = indexContent.contents().find('#BB_0102000001');
            if(DIV_0102000000.length && DIV_0102000001.length) {
              let table1 = DIV_0102000000.contents();
              let table2 = DIV_0102000001.contents();
              if(table1.find('#TableOne').length && table2.find('#print_TableOne').length){
                // 
                let tableOne = dealHtmlPargram(table1.find('#TableOne')[0].innerHTML, '', 'width="100%"');
                let tableTwo = dealHtmlPargram(table1.find('#TableTwo')[0].innerHTML, 'table-box', 'width="100%"');
                let tableContent = {
                  declareType: '增值税',
                  title: table1.find('#TableOne tbody > tr:nth-child(1) > td > h3').text().replace(/\s+/g, ''),
                  html: tableOne + tableTwo,
                  css: cssStyle
                };
                saveTableDetail(tableContent);
                // 
                let print_TableOne = dealHtmlPargram(table2.find('#print_TableOne')[0].innerHTML, '', 'width="100%"');
                let print_TableTwo = dealHtmlPargram(table2.find('#print_TableTwo')[0].innerHTML, 'table-box', 'width="100%"');
                let tableContent1 = {
                  declareType: '增值税',
                  title: table2.find('#print_TableOne tbody > tr:nth-child(1) > td > h3').text().replace(/\s+/g, ''),
                  html: print_TableOne + print_TableTwo,
                  css: cssStyle
                };
                setTimeout(() => {
                  saveTableDetail(tableContent1);
                  indexContent.contents().find('#return_open').click();
                  setTimeout(() => {
                    resolve(true)
                  }, 1000);
                }, 500);
                return true 
              }
            }
          }
          
        }, 1000);
        return true;
      }
    })
  })
}



const asyncTableDetailFjs = async () => {
  window.postMessage({
    event: 'getAsyncTableDetailStartStatus'
  }, '*')
  window.addEventListener(
    'message',
    async function({ data }) {
      if (data.sender !== 'content-script') {
        return false;
      }
      if (data.event === 'getAsyncTableDetailStartStatusBack') {
        if(data.data.isStart) {
          startAsyncTableFjs(data.data);
        }
      }
    }
  )
};
const startAsyncTableFjs = async () => {
  nextTick(() => {
    if(document.querySelector("#sbxxmxDiv > div:nth-child(2) > div.sGrid_div > div:nth-child(2) > div.sGrid_data_div")) {
      let div = document.querySelector("#sbxxmxDiv > div:nth-child(2) > div.sGrid_div > div:nth-child(2) > div.sGrid_data_div");
      if(div.innerText.includes('地方教育附加')) {
        document.querySelector("#sbxxmxDiv > table > tbody > tr > td:nth-child(1) > div > div").click();
        nextTick(() => {
          if(document.querySelector("#ymPrompt_btn_0")) document.querySelector("#ymPrompt_btn_0").click();
          setTimeout(() => {
            window.close();
          }, 2000);
        })
      }
      return true;
    }
  })
}
const asyncTableDetailFjsTable = () => {
  window.postMessage({
    event: 'getAsyncTableDetailStartStatus'
  }, '*')
  window.addEventListener(
    'message',
    async function({ data }) {
      if (data.sender !== 'content-script') {
        return false;
      }
      if (data.event === 'getAsyncTableDetailStartStatusBack') {
        if(data.data.isStart) {
          let table = dealHtmlPargram(document.querySelector("#dydiv > table").innerHTML);
          let tableContent = {
            declareType: '附加税（费）申报',
            title: '纳税申报表',
            html: table,
            css: ''
          };
          saveTableDetail(tableContent);
          window.postMessage(
            {
              event: "baoBiaoDetailBack",
              data: {
                type: 'asyncTable',
                isclose: true,
                lastTime: 2000
              }
            },
            "*"
          );
        }
      }
    }
  )
}
const asyncOpenPage = () => {
  window.postMessage({
    event: 'getAsyncTableDetailStartStatus'
  }, '*')
  window.addEventListener(
    'message',
    async function({ data }) {
      if (data.sender !== 'content-script') {
        return false;
      }
      if (data.event === 'getAsyncTableDetailStartStatusBack') {
        if(data.data.isStart) {
          setTimeout(() => {
            // openFakeWin('null', 'F251000200000176', '按期申报套餐', '102230');
            
          }, 1000);
        }
      }
    }
  )
}
const asyncTableDetail = async () => {
  window.postMessage({
    event: 'getAsyncTableDetailStartStatus'
  }, '*')
  window.addEventListener(
    'message',
    async function({ data }) {
      if (data.sender !== 'content-script') {
        return false;
      }
      if (data.event === 'getAsyncTableDetailStartStatusBack') {
        if(data.data.isStart) {
          startAsyncTable(data.data);
        }
      }
    }
  )
};


export {
  saveTableDetail,
  startAsyncTableDetail,
  asyncTableDetail,
  asyncTableDetailFjs,
  asyncTableDetailFjsTable,
  asyncOpenPage,
};
